package com.xssn.fjnd.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xssn.fjnd.entities.Comment;
import com.xssn.fjnd.content.mapper.CommentMapper;
import com.xssn.fjnd.content.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xssn.util.base.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论信息表 服务实现类
 * </p>
 *
 * @author 线狮少年
 * @since 2023-08-14
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {

    @Override
    public Result findByVideoId(String videoId) {

        //判断视频id是否为空
        if (StringUtils.isEmpty(videoId)) {
            return Result.error("视频不存在");
        }
        List<Comment> list = baseMapper.findByVideoId(videoId);
        return Result.ok(list);
    }

    @Override
    public Result deleteById(String id) {
        //判断传过来的id是否为空
        if (StringUtils.isEmpty(id)) {
            return Result.error("评论ID为空");
        }
        //创建集合存储该id以及子类id
        List<String> ids = new ArrayList<>();
        //存入当前传入的id
        ids.add(id);
        //递归查询子类id
        this.getIds(ids, id);

        //删除集合ids
        baseMapper.deleteBatchIds(ids);

        return Result.ok();
    }

    private void getIds(List<String> ids, String parentId) {
        //查询子评论信息 根据parent_id查询
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<Comment> childrenList = baseMapper.selectList(wrapper);

        //遍历childrenList数组 ，取出每条children的id
        if (CollectionUtils.isNotEmpty(childrenList)) {
            for (Comment comment : childrenList) {
                String id = comment.getId();
                //将id存入ids集合
                ids.add(id);
                //继续调用getIds方法递归该id的子评论
                this.getIds(ids, id);
            }
        }

    }
}
